/*
 * 文  件   名: MessageWidget.java
 * 版         本: docrepository-web(Anttribe). All rights reserved
 * 描         述: <描述>
 * 修   改  人: zhaoyong
 * 修改时 间: 2014年11月24日
 */
package org.anttribe.docrepository.web.message.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.anttribe.docrepository.common.UnifyException;
import org.anttribe.docrepository.common.constants.Keys;
import org.anttribe.docrepository.message.domain.Message;
import org.anttribe.docrepository.message.manager.MessageManager;
import org.anttribe.docrepository.user.domain.UserInfo;
import org.anttribe.docrepository.web.message.convert.MessageConvert;
import org.anttribe.docrepository.web.user.convert.UserInfoConvert;
import org.anttribe.docrepository.web.user.vo.UserInfoVo;
import org.anttribe.saturn.common.utils.ObjectUtils;
import org.anttribe.saturn.component.dataparser.DataParser;
import org.anttribe.saturn.runtime.stereotype.Widget;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 * 处理个人私信的widget
 * 
 * @author zhaoyong
 * @version 2014年11月24日
 */
@Widget(name = "MessageWidget")
@RequestMapping("/user/messages")
public class MessageWidget
{
    /**
     * LOGGER
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(MessageWidget.class);
    
    /**
     * userInfoConvert
     */
    private static UserInfoConvert userInfoConvert = new UserInfoConvert();
    
    /**
     * messageConvert
     */
    private static MessageConvert messageConvert = new MessageConvert();
    
    /**
     * dataParser数据解析器
     */
    private DataParser dataParser = DataParser.getDataParser(DataParser.Parser.Json.name());
    
    /**
     * messageManager
     */
    @Autowired
    private MessageManager messageManager;
    
    /**
     * 个人私信首页
     * 
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @param httpSession HttpSession
     * @return ModelAndView
     */
    @RequestMapping("/index")
    public ModelAndView doMessageUserList(HttpServletRequest request, HttpServletResponse response,
        HttpSession httpSession)
    {
        ModelAndView mv = new ModelAndView();
        
        // 从session中获取用户
        UserInfo userInfo = (UserInfo)httpSession.getAttribute(Keys.USER_SESSION);
        if (!ObjectUtils.isNullOrNone(userInfo))
        {
            // 私信用户列表
            Map<UserInfo, Integer> messageUserMap = null;
            try
            {
                messageUserMap = messageManager.listMessageUser(userInfo.getUserId());
            }
            catch (UnifyException e)
            {
                LOGGER.warn("While getting user received messages, get error: {}", e.getErrorNo());
                mv.addObject("errorNo", e.getErrorNo());
            }
            
            Map<UserInfoVo, Integer> messageUsers = new HashMap<UserInfoVo, Integer>();
            if (!MapUtils.isEmpty(messageUserMap))
            {
                for (Map.Entry<UserInfo, Integer> entry : messageUserMap.entrySet())
                {
                    messageUsers.put(userInfoConvert.convertToVo(entry.getKey()), entry.getValue());
                }
            }
            
            mv.addObject("messageUsers", messageUsers);
        }
        mv.setViewName("message/messages");
        
        return mv;
    }
    
    /**
     * 与用户聊天列表
     * 
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @param httpSession HttpSession
     * @throws IOException
     */
    @RequestMapping("/listUserMessages")
    public void doUserMessageList(HttpServletRequest request, HttpServletResponse response, HttpSession httpSession)
        throws IOException
    {
        // 从session中获取用户
        UserInfo userInfo = (UserInfo)httpSession.getAttribute(Keys.USER_SESSION);
        if (!ObjectUtils.isNullOrNone(userInfo))
        {
            // 用户好友列表
            List<Message> userMessageList = null;
            try
            {
                userMessageList = null; // messageManager.list
            }
            catch (UnifyException e)
            {
                LOGGER.warn("While getting user messages, get error: {}", e.getErrorNo());
            }
            
            // 输出json
            String jsonString = "[]";
            if (!CollectionUtils.isEmpty(userMessageList))
            {
                jsonString = dataParser.parserToString(messageConvert.convertToVo(userMessageList), null);
            }
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.write(jsonString);
        }
    }
    
    /**
     * 用户接收的私信列表
     * 
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @param httpSession HttpSession
     * @return ModelAndView
     */
    @RequestMapping("/receivedMessages")
    public ModelAndView doUserReceivedMessageList(HttpServletRequest request, HttpServletResponse response,
        HttpSession httpSession)
    {
        ModelAndView mv = new ModelAndView();
        
        // 从session中获取用户
        UserInfo userInfo = (UserInfo)httpSession.getAttribute(Keys.USER_SESSION);
        if (!ObjectUtils.isNullOrNone(userInfo))
        {
            // 用户私信列表
            List<Message> messageList = null;
            try
            {
                messageList = messageManager.listReceivedMessages(userInfo.getUserId(), null);
            }
            catch (UnifyException e)
            {
                LOGGER.warn("While getting user received messages, get error: {}", e.getErrorNo());
                mv.addObject("errorNo", e.getErrorNo());
            }
            mv.addObject("messageList", messageList);
        }
        mv.setViewName("message/receivedMessages");
        
        return mv;
    }
}